package com.eobard.config.mq;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eobard.entity.MqMessage;
import com.eobard.service.MqMessageService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Case;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @Author: Eobard Gu
 * @Date: 2025-07-17
 * @Description: TODO
 */
@Component
@Slf4j
public class MQProducerAckConfig implements RabbitTemplate.ReturnsCallback, RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    @PostConstruct
    public void init() {
        //注意:这里的Return回调比Confirm回调先执行
        rabbitTemplate.setConfirmCallback(this);    //设置Confirm回调函数(交换机是否收到)
        rabbitTemplate.setReturnsCallback(this);    //启用Return回调(队列是否收到)
        rabbitTemplate.setMandatory(true);  //开启消息退回机制:消息发送到了交换机但路由不到任何队列,把消息退回给生产者

    }



    /**
     * 表示消息是否正确发送到了交换机上
     *
     * @param correlationData 消息的载体
     * @param ack             判断是否发送到交换机上
     * @param cause           原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        MqMessage mqMessage = null;
        if (!ObjectUtils.isEmpty(correlationData)) {
            String correlationId = correlationData.getId();
            //根据最后一次发送id查询消息
            mqMessage = mqMessageService.getOne(new LambdaQueryWrapper<MqMessage>().eq(MqMessage::getLastCorrelationId, correlationId));
        }
        //回调返回ack
        if (ack) {
            if (null != mqMessage) {
                //如果不存在路由则删去消息这条记录
                if (checkNotExistRoutingKey(correlationData.getReturned())) {
                    log.error("路由:【{}】不存在,正在删除DB记录,correlationId:【{}】", mqMessage.getRoutingKey(), correlationData.getId());
                    mqMessageService.removeById(mqMessage.getId());
                } else {
                    //更新状态
                    mqMessage.setStatus(true);
                    mqMessageService.updateById(mqMessage);
                    log.info("\n" +
                                    "================Confirm-Callback:⬇️=====================\n\n" +
                                    "生产者:{} 消息发送成功!\n" +
                                    "exchange: {},        routingKey: {},\n" +
                                    "message:  {}\n\n" +
                                    "================Confirm-Callback:⬆️=====================",
                            mqMessage.getLastCorrelationId(),
                            mqMessage.getExchangeName(),
                            mqMessage.getRoutingKey(),
                            new String(mqMessage.getMessageBody().getBytes(), StandardCharsets.UTF_8));
                }
            }
        }
        //回调没有返回ack
        else {
            log.error("消息发送失败!原因:{}", cause);
            //如果不存在交换机则删去消息这条记录
            if (checkNotExistExchange(cause)) {
                log.error("交换机:【{}】不存在,正在删除DB记录,correlationId:【{}】", mqMessage.getExchangeName(), correlationData.getId());
                mqMessageService.remove(new LambdaQueryWrapper<MqMessage>().eq(MqMessage::getLastCorrelationId, correlationData.getId()));
            } else {
                if (null != mqMessage) {
                    //重新发送消息id
                    String lastCorrelationId = UUID.randomUUID().toString();
                    //更新correlationId和状态
                    mqMessage.setLastCorrelationId(lastCorrelationId);
                    mqMessage.setStatus(false);
                    mqMessageService.updateById(mqMessage);
                    //手动补偿:再次发送消息
                    rabbitTemplate.convertAndSend(mqMessage.getExchangeName(),
                            mqMessage.getRoutingKey(),
                            mqMessage.getMessageBody(),
                            new CorrelationData(lastCorrelationId)
                    );
                    //TODO:如果再次发送失败使用定时任务去查询status=false并且deleted=false的记录去补偿消息,可以在数据库中设置重试次数等
                }
            }
        }
    }

    /**
     * 消息如果没有正确发送到队列中，则会走这个方法！如果消息被正常处理，则这个方法不会走！
     *
     * @param returnedMessage
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        String exchange = returnedMessage.getExchange();
        String routingKey = returnedMessage.getRoutingKey();
        String message = new String(returnedMessage.getMessage().getBody(), StandardCharsets.UTF_8);
        log.info("\n" +
                        "================Returned-Callback:⬇️===============\n\n" +
                        "路由不存在:\n" +
                        "exchange: {},\t\troutingKey: {},\n" +
                        "replyCode:{},\t\treplyText: {},\n" +
                        "message:  {}\n\n" +
                        "================Returned-Callback:⬆️===============",
                exchange, routingKey, returnedMessage.getReplyCode(), returnedMessage.getReplyText(), message);
    }


    //检查交换机是否存在
    private boolean checkNotExistExchange(String cause) {
        cause = cause.toLowerCase();
        return (cause.contains("reply-code=404") && cause.contains("reply-text=NOT_FOUND".toLowerCase()))
                ||
                (cause.contains("404") && cause.contains("NOT_FOUND".toLowerCase()))
                ||
                (cause.contains("no exchange"));
    }

    //检查路由是否存在
    private boolean checkNotExistRoutingKey(ReturnedMessage returned) {
        //ReturnedMessage只有在路由或者交换机有问题时才不会为null
        if (ObjectUtils.isEmpty(returned)) return false;
        int replyCode = returned.getReplyCode();
        String replyText = returned.getReplyText();
        return replyCode == 312 && replyText.toUpperCase().contains("NO_ROUTE");
    }
}
